<html>

 <head><title>Post message tests</title>
 <script>
  // Send a message to our opener, and it will reply.
  function postToOpener(msg, origin) {
    window.opener.postMessage(msg, origin);
    return true;
  }

  // Send a message to our opener's opener.
  function postToOpenerOfOpener(msg, origin) {
    window.opener.opener.postMessage(msg, origin);
    return true;
  }

  // Send a message to our parent's opener.
  function postToOpenerOfParent(msg, origin) {
    parent.opener.postMessage(msg, origin);
    return true;
  }

  // Send a message to our parent's opener.
  function postToOpenerOfSibling(siblingName, msg, origin) {
    parent.frames[siblingName].opener.postMessage(msg, origin);
    return true;
  }

  // Send a message to a window named "foo".
  function postToFoo(msg) {
    var w = window.open("", "foo");
    w.postMessage(msg, "*");
    return true;
  }
  
  function openPopup(url) {
    popup = window.open(url);
  }

  function postToPopup(msg) {
    popup.postMessage(msg, "*");
    return true;
  }

  // Send a message to parent.
  function postToParent(msg) {
    parent.postMessage(msg, "*");
    return true;
  }

  // Send a message to sibling.
  function postToSibling(msg, sibling) {
    parent.frames[sibling].postMessage(msg, "*");
    return true;
  }

  // Send a message to a subframe of window named "foo".
  function postToFooFrame(msg) {
    var w = window.open("", "foo");
    w.frames[0][0].postMessage(msg, "*");
    return true;
  }

  function registerUnload() {
    window.addEventListener('unload', function(e) {
	postToParent("message-from-unload", "*");
    });
  }

  // Listen to incoming messages.
  var receivedMessages = 0;
  var receivedMessagesWithPort = 0;
  window.addEventListener("message", messageReceived, false);
  function messageReceived(event) {
    receivedMessages++;
    if (event.data === "2-1-reply") {
      event.source.postMessage("msg4", "*");
    } else if (event.data === "subframe-msg") {
      event.source.postMessage("subframe-msg-reply", "*");
    } else if (event.data === "subframe-msg-reply") {
      domAutomationController.send("done-" + window.name);
    }
    if (event.ports && event.ports.length > 0) {
      receivedMessagesWithPort++;
      var port = event.ports[0];
      port.start();
      port.postMessage("msg-back-via-port");
      // Change the title to generate a notification.
      document.title = event.data.message;
    } else {
      document.title = event.data;
    }
  }
 </script>
 </head>

</html>
